//
//  MyHouseListVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/2.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "MyHouseListVC.h"
#import "MyHouseInfoBottomCell.h"
#import "MyHouseInfoTopCell.h"

#import "HouseParameSub.h"
#import "HouseParameterModel.h"

#import "PulishRentInfoVC.h"

#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
@interface MyHouseListVC ()<MyHouseInfoCellDelegate>

@property (nonatomic, assign) NSInteger curpage;

@property (nonatomic, assign) NSString *pageCount;

@property (nonatomic, assign) NSString *totalCount;

@property (nonatomic, strong) NSMutableArray<HouseParameterModel *> *dataModels;

@property (nonatomic, strong) NSString *payType;

@property (nonatomic, strong) NSIndexPath *selectIndex;
@end

@implementation MyHouseListVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"我的房源信息";
    
    self.groupTableView.backgroundColor = viewBgGrey;
    
    self.groupTableView.rowHeight = UITableViewAutomaticDimension;
    
    self.groupTableView.estimatedRowHeight = 100;
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyHouseInfoTopCell class]) bundle:nil] forCellReuseIdentifier:[MyHouseInfoTopCell identifierStr]];
    
    [self.groupTableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyHouseInfoBottomCell class]) bundle:nil] forCellReuseIdentifier:[MyHouseInfoBottomCell identifierStr]];
    
    MJWeakSelf
    self.groupTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.groupTableView.mj_header beginRefreshing];
    
    self.groupTableView.mj_footer = [XMGRefreshFooter footerWithRefreshingBlock:^{
        
        [weakSelf loadMoreData];
        
    }];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didXiuGaiFangYuang) name:@"DidXiuGaiFangYuang" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];
    
}



- (void)WXApiDidSuccessNotification{
    
    [SVProgressHUD showSuccessWithStatus:@"支付成功!"];

    HouseParameterModel *model = self.dataModels[self.selectIndex.section];
    
    model.pay_status = @"2";
    
    [self.groupTableView reloadData];

}

- (void)WXApiDidFailNotification{
    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
    
}

- (void)AlipayDidSuccessNotification{
    
    [SVProgressHUD showSuccessWithStatus:@"支付成功!"];
    
    HouseParameterModel *model = self.dataModels[self.selectIndex.section];
    
    model.pay_status = @"2";
    
    [self.groupTableView reloadData];
}


- (void)AlipayDidFailNotification{
    
    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
}


- (void)dealloc{

    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}





- (void)didXiuGaiFangYuang{
    
    [self loadData];
    
}



//合租 . 东津世纪城 三室一厅

- (void)loadData{
    
    self.curpage = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"page"] = @"1";
    parameters[@"pagesize"] = @"20";
    parameters[@"uid"] = myViewModel.user.uid;

    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"House/myHouse" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
//            MYJSONSTR
//            _model.lastString
            
//           [[responseObject[@"data"][@"house"] firstObject]  propertyCode];
            
            weakSelf.pageCount = responseObject[@"data"][@"page_count"];
            
            weakSelf.totalCount = responseObject[@"data"][@"total_count"];
            
            
            weakSelf.dataModels = [HouseParameterModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"house"]];
            
            
            if (myViewModel.parameterModel != nil) {
                for (HouseParameterModel *model in weakSelf.dataModels) {
                    
                    model.language = myViewModel.parameterModel.language;
                    model.huxing = myViewModel.parameterModel.huxing;
                    model.fukuan = myViewModel.parameterModel.fukuan;
                    model.rentingStyle = myViewModel.parameterModel.rentingStyle;
                    model.decorateStyle = myViewModel.parameterModel.decorateStyle;
                    model.houseStyle = myViewModel.parameterModel.houseStyle;
                    model.position = myViewModel.parameterModel.position;
                    
                    [weakSelf setupValues:model];
                }
            }
            
            
            [weakSelf.groupTableView.mj_footer resetNoMoreData];
            
            if ([weakSelf.totalCount isEqualToString:@"0"]) {
                
                
            } else {
                
                if ([weakSelf.pageCount isEqualToString:@"1"]) {
                    
                    [weakSelf.groupTableView.mj_footer endRefreshingWithNoMoreData];
                    
                }
            }
            
            [weakSelf.groupTableView.mj_header endRefreshing];
            
            
            
            [weakSelf.groupTableView reloadData];
            
            
        } else {
            
            [weakSelf.groupTableView.mj_header endRefreshing];

            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
  
    
}


- (void)setupValues:(HouseParameterModel *)model{
   
    for (ProvinceModel *province in myViewModel.areas) {
        
        if ([province.province_id isEqualToString:@"43"]) {
            NSLog(@"%@",province.province_name);
            
            
            
        }
        
        if ([province.province_id isEqualToString:model.province_id]) {
            
            model.province = province.province_name;
            
            for (CitysModel *city in province.citys) {
                
                if ([city.city_id isEqualToString:model.city_id]){
                    
                    model.city = city.city_name;
                    
                }
                
            }
            
        }
        
        
        
    }
    
    if (model.province.length > 0) {
        
        model.lastString = [NSString stringWithFormat:@"%@-%@",model.province,model.city];

    } else {
        
        model.lastString = nil;

    }
    
    
    
    
    model.renting_style_name = model.renting_style;
    
    model.huXing_name = model.apartment;
    
    
    for (HouseParameSub *sub in model.houseStyle) {
        if ([sub.class_id isEqualToString:model.house_type]) {
            
            model.house_type_name = sub.name;
        }
    }
    
    
    
    for (HouseParameSub *sub1 in model.position) {
        if ([sub1.class_id isEqualToString:model.house_face]) {
            model.house_face_name = sub1.name;
        }
    }
    
    
    for (HouseParameSub *sub1 in model.fukuan ) {
        if ([sub1.class_id isEqualToString:model.pay_class_id]) {
            model.pay_class_method = sub1.name;
        }
    }
    
    
    NSMutableString *areaStr = [NSMutableString string];
    for (HouseParameSub *sub2 in model.language) {
        if ([model.house_language containsString:sub2.class_id]) {
            
            [areaStr appendString:sub2.name];
            
            [areaStr appendString:@","];

        }
    }
    
    
    model.house_language_name = [areaStr substringToIndex:areaStr.length - 1];

//    if (model.house_decorate == nil) {
//
//        model.house_decorate_name = @"精装修";
//
//        model.house_decorate = @"25";
//
//    } else {
    
        for (HouseParameSub *sub2 in model.decorateStyle) {
            
            if ([sub2.class_id isEqualToString:model.house_decorate]) {
                
                model.house_decorate_name = sub2.name;
            }
        }
    
    
//    }
    
    
   
}


- (void)loadMoreData{
    
    self.curpage ++;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pagesize"] = @"20";
    parameters[@"uid"] = myViewModel.user.uid;
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)self.curpage];
    
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools] sendRequestWithHttpMethod:GET_METHOD URLPath:@"House/myHouse" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSMutableArray<HouseParameterModel *> *temp = [HouseParameterModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"house"]];
            
            if (myViewModel.parameterModel != nil) {
                
                for (HouseParameterModel *model in temp) {
                    
                    model.language = myViewModel.parameterModel.language;
                    model.huxing = myViewModel.parameterModel.huxing;
                    model.fukuan = myViewModel.parameterModel.fukuan;
                    model.rentingStyle = myViewModel.parameterModel.rentingStyle;
                    model.decorateStyle = myViewModel.parameterModel.decorateStyle;
                    model.houseStyle = myViewModel.parameterModel.houseStyle;
                    model.position = myViewModel.parameterModel.position;
                    
                    [weakSelf setupValues:model];

                }
            }
            
            [weakSelf.dataModels addObjectsFromArray:temp];
            
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *language;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *huxing;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *fukuan;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *rentingStyle;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *decorateStyle;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *houseStyle;
//            @property (nonatomic, strong) NSArray<HouseParameSub *> *position;
            
            if (weakSelf.pageCount.integerValue == self.curpage) {
                
                [weakSelf.groupTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else {
                
                [weakSelf.groupTableView.mj_footer endRefreshing];
                
                
            }
            
            
            [weakSelf.groupTableView reloadData];
            
        }else{
            
            [weakSelf.groupTableView.mj_footer endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
    }];
    
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModels == nil) {
        
        return 0;

    } else {
        
        return self.dataModels.count;

    }
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (self.dataModels == nil) {
        
        return 0;
        
    } else {
        
        return 2;
        
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 0) {
        
        MyHouseInfoTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[MyHouseInfoTopCell identifierStr]];
        
        tableCell.model = self.dataModels[indexPath.section];
        
        return tableCell;
        
    } else {
        
        MyHouseInfoBottomCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[MyHouseInfoBottomCell identifierStr]];
        
        tableCell.index = indexPath;
        
        tableCell.delegate = self;
        
        tableCell.model = self.dataModels[indexPath.section];
        
        return tableCell;
    }
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    if (section == 0) {
        
        return 0.00001;
        
    } else {
        
        return 12;
    }
    
    
    
    
}



- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]init];
    temp.backgroundColor = [UIColor whiteColor];
    return temp;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]init];
    temp.backgroundColor = viewBgGrey;
    return temp;
    
    
    
}




- (void)editBtnDidClickWith:(NSIndexPath *)index{
    
    HouseParameterModel *model = self.dataModels[index.section];
    
    PulishRentInfoVC *tempVC = [[PulishRentInfoVC alloc]init];
    
    
     tempVC.identifiStr = @"88888";
    
    tempVC.parameterModel = model;
    
   
    
    [self.navigationController pushViewController:tempVC animated:YES];
    
}



- (void)deleBtnDidClickWith:(NSIndexPath *)index{
    
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:@"确定删除该房源信息吗?" preferredStyle:UIAlertControllerStyleAlert];
    
    MJWeakSelf;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        HouseParameterModel *model = self.dataModels[index.section];
        
        [weakSelf deletAddressWithID:model.house_id];
        
        [weakSelf.dataModels removeObjectAtIndex:index.section];
        
        if (weakSelf.dataModels.count > 0) {
            
            
            
        }else{
            
        
            
        }
        
        
        [weakSelf.groupTableView reloadData];
        
        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    
    [contr addAction:action2];
    
    [contr addAction:action1];
    
    [self presentViewController:contr animated:YES completion:nil];

    
    
}




- (void)deletAddressWithID:(NSString *)addressId{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    
    parameters[@"house_id"] = addressId;

//    NSLog(@"%@",addressId);
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"House/deleteHouse" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
//NSLog(@"%@",responseObject);
            
            [SVProgressHUD showSuccessWithStatus:responseObject[@"data"]];
            
        }else{
            
//NSLog(@"%@",error);
            
        }
        
        
    }];
    
    
    
    
}




- (void)payBtnDidClickWith:(NSIndexPath *)index{
    
    self.selectIndex = index;
    
    MJWeakSelf;
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:@"选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [contr addAction:action0];
    
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"1";
        
         [self wachatPay];
        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"2";
        
         [self alipayPayWith];
        
    }];
    
    
    
    [contr addAction:action1];
    [contr addAction:action2];
    
    
    [self presentViewController:contr animated:YES completion:nil];
    
    
    
}


- (void)alipayPayWith{
    
    
    HouseParameterModel *model = self.dataModels[self.selectIndex.section];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = model.pay_rmb;
    parameters[@"out_trade_no"] = model.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}


- (void)wachatPay{
    
    HouseParameterModel *model = self.dataModels[self.selectIndex.section];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = model.pay_rmb;
    parameters[@"out_trade_no"] = model.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}



- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
